package com.xhsj.user.hr.system.web;


import com.google.common.collect.Maps;
import com.xhsj.user.config.UploadPathConfig;
import com.xhsj.user.hr.system.entity.UploadFile;
import com.xhsj.user.lsm.entity.TbContractFile;
import com.xhsj.user.lsm.mapper.TbContractFileMapper;
import com.xhsj.user.lsm.mapper.TbContractOpinionFileMapper;
import com.xhsj.user.pms.oareply.entity.TbPamPatentOaCorrection;
import com.xhsj.user.pms.oareply.mapper.TbPamPatentOaCorrectionFileMapper;
import com.xhsj.user.pms.oareply.mapper.TbPamPatentOaCorrectionMapper;
import com.xhsj.user.pms.patent.domain.BillFile;
import com.xhsj.user.pms.patent.domain.OpinionFile;
import com.xhsj.user.pms.patent.domain.PatentFile;
import com.xhsj.user.pms.patent.domain.TemplateFile;
import com.xhsj.user.pms.patent.mapper.PatentFileMapper;
import com.xhsj.user.pms.patent.mapper.TbPamPatentOverseasFileMapper;
import com.xhsj.user.sms.announcement.service.TbEnterpriseAnnouncementFileService;
import com.xhsj.user.utils.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.data.annotation.Id;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.Map;

@Api(tags = "文件")
@Slf4j
@Controller
@RequestMapping(value = "/file")
@CrossOrigin(origins = "*", maxAge = 3600)
public class FileController {

    private final ResourceLoader resourceLoader;

    private static final String loggerName = FileController.class.getName();

    @Autowired
    public FileController(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }

    @Autowired
    private UploadPathConfig uploadPath;

    @Autowired
    TbContractOpinionFileMapper tbContractOpinionFileMapper;

    @Autowired
    private TbContractFileMapper tbContractFileMapper;

    @Autowired
    private PatentFileMapper patentFileMapper;

    @Autowired
    private TbPamPatentOverseasFileMapper tbPamPatentOverseasFileMapper;

    @Autowired
    private TbPamPatentOaCorrectionFileMapper tbPamPatentOaCorrectionFileMapper;

    @Autowired
    private TbEnterpriseAnnouncementFileService tbEnterpriseAnnouncementFileService;

    private static String suffix = "xls,xlsx,doc,docx,pdf,txt,bmp,jpg,jpeg,png,gif,rar,zip,7z";

    /**
     * 请购意向或方案文件
     *
     * @return
     */
    @RequestMapping(value = {"/upload"}, method = RequestMethod.POST, consumes = "multipart/form-data")
    @ApiOperation(value = "上传文件", notes = "上传文件")
    @ResponseBody
    public Message uploadFile(@RequestParam("file") MultipartFile file) {
        try {
            log.info("上传物料相关的文件，{},{}", file);
            if (StringUtils.isNull(file)) {
                return Message.error(1, "上传文件失败，文件为空！");
            }
            String originalFilename = file.getOriginalFilename();
            System.err.println(originalFilename);
            String path = "erp-user";
            String newFileName = this.uploadFile(path, file);
            UploadFile uploadFile = new UploadFile();
            uploadFile.setFileName(file.getOriginalFilename());
            uploadFile.setCreateBy(UserUtils.getLoginAppUser().getUserId());
            uploadFile.setOriginalName(originalFilename);
            uploadFile.setFileUrl("/file/download" + uploadPath.getDirectory() + newFileName);
            uploadFile.setDelUrl(uploadFile.getFileUrl());
            uploadFile.setCreateDate(new Date());
            log.debug(uploadFile.toString());
            return Message.success("上传文件成功", uploadFile);
        } catch (Exception e) {
            log.error("上传文件失败:{}", e);
            return Message.error(1, "上传文件失败！");
        }
    }

    /**
     * 上传缴费文件
     *
     * @return
     */
    @RequestMapping(value = {"/uploadBillFile"}, method = RequestMethod.POST, consumes = "multipart/form-data")
    @ApiOperation(value = "上传缴费文件", notes = "上传缴费文件")
    @ResponseBody
    public Message uploadBillFile(@RequestParam("file") MultipartFile file) {
        try {
            if (StringUtils.isNull(file)) {
                return Message.error(1, "上传文件失败，文件为空！");
            }
            String path = "erp-user";
            String newFileName = this.uploadFile(path, file);
            BillFile billFile = new BillFile();
            billFile.setFileName(file.getOriginalFilename());
            billFile.setFileUrl("/file/download" + uploadPath.getDirectory() + newFileName);
            billFile.setDelUrl(billFile.getFileUrl());
            billFile.setUploadTime(new Date());
            System.err.println(billFile.toString());
            return Message.success("上传文件成功", billFile);
        } catch (Exception e) {
            log.error("上传文件失败:{}", e);
            return Message.error(1, "失败");
        }
    }

    /**
     * 上传交底书文件
     *
     * @return
     */
    @RequestMapping(value = {"/uploadDisclosureFile"}, method = RequestMethod.POST, consumes = "multipart/form-data")
    @ApiOperation(value = "上传文件", notes = "上传文件")
    @ResponseBody
    public Message uploadDisclosureFile(@RequestParam("file") MultipartFile file, @RequestParam(value = "fileType", required = false) String fileType) {
        try {
            log.info("上传文件参数，{},{}", file, fileType);
            if (StringUtils.isNull(file)) {
                return Message.error(1, "上传文件失败，文件为空！");
            }
            String path = "erp-user";
            String newFileName = this.uploadFile(path, file);
            PatentFile upFile = new PatentFile();
            upFile.setFileName(file.getOriginalFilename());
            upFile.setUrl("/file/download" + uploadPath.getDirectory() + newFileName);
            upFile.setDelUrl(upFile.getUrl());
            upFile.setUploadTime(new Date());
            upFile.setFileType(StringUtils.toInteger(fileType));
            log.debug(upFile.toString());
            return Message.success("上传文件成功", upFile);
        } catch (Exception e) {
            log.error("上传文件失败:{}", e);
            return Message.error(1, "失败");
        }
    }

    /**
     * 意见文件
     *
     * @return
     */
    @RequestMapping(value = {"/uploadOpinionFile"}, method = RequestMethod.POST, consumes = "multipart/form-data")
    @ApiOperation(value = "意见文件", notes = "意见文件")
    @ResponseBody
    public Message uploadOpinionFile(@RequestParam("file") MultipartFile file) {
        try {
            if (StringUtils.isNull(file)) {
                return Message.error(1, "上传意见文件，文件为空！");
            }

            String path = "erp-user";
            String newFileName = this.uploadFile(path, file);
            OpinionFile opinionFile = new OpinionFile();
            opinionFile.setFileName(file.getOriginalFilename());
            opinionFile.setUrl("/file/download" + uploadPath.getDirectory() + newFileName);
            opinionFile.setDelUrl(opinionFile.getUrl());
            opinionFile.setUploadTime(new Date());
            return Message.success("上传文件成功", opinionFile);
        } catch (Exception e) {
            log.error("上传文件失败:{}", e);
            return Message.error(1, "失败");
        }
    }


    /**
     * 模板文件
     *
     * @return
     */
    @RequestMapping(value = {"/uploadTemplateFile"}, method = RequestMethod.POST, consumes = "multipart/form-data")
    @ApiOperation(value = "模板文件", notes = "模板文件")
    @ResponseBody
    public Message uploadTemplateFile(@RequestParam("file") MultipartFile file, @RequestParam("fileType") String fileType) {
        try {
            if (StringUtils.isNull(file)) {
                return Message.error(1, "上传模板文件，文件为空！");
            }
            if (StringUtils.isNull(fileType)) {
                return Message.error(1, "上传模板文件，文件类型参数为空！");
            }
//            if (!validSuffix(file.getOriginalFilename())) {
//                return  Message.error( 1,"上传文件类型错误,支持上传文件类型:"+suffix);
//            }
            String path = "erp-user";
            String newFileName = this.uploadFile(path, file);
            TemplateFile templateFile = new TemplateFile();
            templateFile.setTemplateFileName(newFileName);
            templateFile.setFileUrl("/file/download" + uploadPath.getDirectory() + newFileName);
            templateFile.setUploadTime(new Date());
            templateFile.setDelUrl(templateFile.getFileUrl());
            templateFile.setFileType(fileType);
            return Message.success("上传文件成功", templateFile);
        } catch (Exception e) {
            log.error("上传文件失败:{}", e);
            return Message.error(1, "失败");
        }
    }


    /**
     * 上传检索文件
     *
     * @return
     */
    @RequestMapping(value = {"/uploadRetrievalFile"}, method = RequestMethod.POST, consumes = "multipart/form-data")
    @ApiOperation(value = "上传检索文件", notes = "上传检索文件")
    @ResponseBody
    public Message uploadRetrievalFile(@RequestParam("file") MultipartFile file,
                                       @RequestParam(value = "discId") String discId,
                                       @RequestParam(value = "fileType") Integer fileType,
                                       @RequestParam(value = "ownerAs") String ownerAs
    ) {
        try {
            if (StringUtils.isNull(file)) {
                return Message.error(1, "上传检索文件失败，文件为空！");
            }
            String path = "erp-user";
            String newFileName = this.uploadFile(path, file);
            PatentFile upFile = new PatentFile();
            upFile.setFileName(file.getOriginalFilename());
            upFile.setUrl("/file/download" + uploadPath.getDirectory() + newFileName);
            upFile.setDelUrl(upFile.getUrl());
            upFile.setUploadTime(new Date());
            String uuid = IdGen.generateUUID();
            upFile.setPatentFileId(uuid);
            upFile.setDiscId(discId);
            upFile.setFileType(fileType);
            upFile.setOwnerAs(ownerAs);
            int insert = patentFileMapper.insert(upFile);
            if (insert != 1) {
                return Message.error(1, "失败");
            }
            log.debug(upFile.toString());
            return Message.success("上传文件成功", upFile);
        } catch (Exception e) {
            log.error("上传文件失败:{}", e);
            return Message.error(1, "失败");
        }
    }


    /**
     * 申请文件
     *
     * @return
     */
    @RequestMapping(value = {"/uploadApplyFile"}, method = RequestMethod.POST, consumes = "multipart/form-data")
    @ApiOperation(value = "上传申请文件", notes = "上传申请文件")
    @ResponseBody
    public Message uploadApplyFile(@RequestParam("file") MultipartFile file) {
        try {
            if (StringUtils.isNull(file)) {
                return Message.error(1, "上传合同文件，文件为空！");
            }
            if (!validSuffix(file.getOriginalFilename())) {
                return Message.error(1, "上传文件类型错误,支持上传文件类型:" + suffix);
            }
            String path = "erp-user";
            String newFileName = this.uploadFile(path, file);
            Map<String, Object> map = Maps.newHashMap();
            map.put("fileName", file.getOriginalFilename());
            map.put("fileUrl", "/file/download" + uploadPath.getDirectory() + newFileName);
            map.put("delUrl", "/file/download" + uploadPath.getDirectory() + newFileName);
            map.put("createDate", new Date());
            map.put("updateDate", new Date());
            return Message.success("上传文件成功", map);
        } catch (Exception e) {
            log.error("上传文件失败:{}", e);
            return Message.error(1, "失败");
        }
    }

    /**
     * 请购意向或方案文件
     *
     * @return
     */
    @RequestMapping(value = {"/uploadPurchaseFile"}, method = RequestMethod.POST, consumes = "multipart/form-data")
    @ApiOperation(value = "上传采购文件,采购清单、询价单、采购计划、采购合同", notes = "上传采购文件")
    @ResponseBody
    public Message uploadPurchaseFile(@RequestParam("file") MultipartFile file) {
        try {
            log.info("上传采购文件，{},{}", file);
            if (StringUtils.isNull(file)) {
                return Message.error(1, "上传文件失败，文件为空！");
            }
            if (!validSuffix(file.getOriginalFilename())) {
                return Message.error(1, "上传文件类型错误,支持上传文件类型:" + suffix);
            }
            String path = "erp-user";
            String newFileName = this.uploadFile(path, file);
            UploadFile uploadFile = new UploadFile();
            uploadFile.setFileName(file.getOriginalFilename());
            uploadFile.setFileUrl("/file/download" + uploadPath.getDirectory() + newFileName);
            uploadFile.setDelUrl(uploadFile.getFileUrl());
            uploadFile.setCreateDate(new Date());

            log.debug(uploadFile.toString());
            return Message.success("上传文件成功", uploadFile);
        } catch (Exception e) {
            log.error("上传文件失败:{}", e);
            return Message.error(1, "上传文件失败！");
        }
    }

    /**
     * 企业公告
     *
     * @return
     */
    @RequestMapping(value = {"/uploadEnterpriseAnnouncementFile"}, method = RequestMethod.POST, consumes = "multipart/form-data")
    @ApiOperation(value = "上传企业公告文件", notes = "上传企业公告文件")
    @ResponseBody
    public Message uploadEnterpriseAnnouncementFile(@RequestParam("file") MultipartFile file) {
        try {
            log.info("上传企业公告文件，{},{}", file);
            if (StringUtils.isNull(file)) {
                return Message.error(1, "上传文件失败，文件为空！");
            }

            if (!validSuffix(file.getOriginalFilename())) {
                return Message.error(1, "上传文件类型错误,支持上传文件类型:" + suffix);
            }
            String path = "Announcement";
            String newFileName = this.uploadFile(path, file);
            UploadFile uploadFile = new UploadFile();
            uploadFile.setFileName(file.getOriginalFilename());
            uploadFile.setFileUrl("/file/download" + uploadPath.getDirectory() + newFileName);
            uploadFile.setDelUrl(uploadFile.getFileUrl());
            uploadFile.setCreateDate(new Date());

            log.debug(uploadFile.toString());
            return Message.success("上传文件成功", uploadFile);
        } catch (Exception e) {
            log.error("上传文件失败:{}", e);
            return Message.error(1, "上传文件失败！");
        }
    }


    private String uploadFile(String path, MultipartFile file) throws IOException {
        String date = DateUtils.formatDate(new Date(), "yyyy-MM-dd");
        String upload = uploadPath.getTemp() + path + "/" + date;
        File dirFile1 = new File(upload);
        if (!dirFile1.exists() && !dirFile1.isDirectory()) {
            dirFile1.mkdirs();
        }

        int fixPosition = file.getOriginalFilename().lastIndexOf(".");
        String newFileName = IdGen.uuid() + "." + file.getOriginalFilename().substring(fixPosition + 1);

//        String newFileName = file.getOriginalFilename().substring(0, fixPosition)
//                + "_" + System.currentTimeMillis() + "."
//                + file.getOriginalFilename().substring(fixPosition + 1);

        Path filePath = Paths.get(upload, newFileName);

        if (!file.isEmpty()) {
            Files.copy(file.getInputStream(), filePath);
        } else {
            log.debug(file.getName() + "file is empty!");
        }

        return path + "/" + date + "/" +newFileName;
    }

    public boolean validSuffix(String fileName) {
        String[] split = suffix.split(",");
        for (String s : split) {
            if (fileName.endsWith(s)) {
                return true;
            }
        }
        return false;
    }

    @ApiOperation(value = "下载附件", notes = "下载附件")
    @ResponseBody
    @RequestMapping(value = {"/download/**/{path}"}, method = RequestMethod.GET)
    public ResponseEntity<?> getFile(
            @ApiParam(value = "文件路径名称。", required = true) @PathVariable String path,
            HttpServletRequest request) {
        log.info("下载附件参数，{}", path);
        try {
            // uploadPath.getPath(): /usr/local/AppRun/oa/hr/files
            path = uploadPath.getPath() + "/" + request.getServletPath().substring(request.getServletPath().lastIndexOf("download/") + 9);
            String[] arry = path.split("/");
            String filename = arry[arry.length - 1];
            Path filePath = Paths.get(path);
            FileSystemResource file = new FileSystemResource(filePath.toFile());
            boolean exists = file.exists();
            if (!exists) {
                return ResponseEntity.ok()
                        .contentType(MediaType.APPLICATION_JSON)
                        .body("文件不存在或已被删除！");
            }

            HttpHeaders headers = new HttpHeaders();
            if (isAttechment(filename)) {
                headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
                // 强制浏览器下载
                headers.add("Content-Disposition",
                        String.format("attachment; filename=\"%s\"", java.net.URLEncoder.encode(filename, "UTF-8")));
                headers.add("Pragma", "no-cache");
                headers.add("Expires", "0");
                headers.add("Content-Length", String.valueOf(file.contentLength()));
            }
            String medType = getMediaType(filename);
            return ResponseEntity.ok().headers(headers).contentLength(file.contentLength())
                    .contentType(MediaType.parseMediaType(medType))
                    .body(resourceLoader.getResource("file:" + filePath));
        } catch (Exception e) {
            log.error("download file error!", e);
            return ResponseEntity.notFound().build();
        }

    }


    @ApiOperation(value = "删除文件信息", notes = "删除文件信息。")
    @ResponseBody
    @RequestMapping(value = {"/delete"}, method = RequestMethod.GET)
    public Message deleteFile(
            @ApiParam(value = "文件路径名称。", required = true) @RequestParam("path") String path, HttpServletRequest request) {
        try {
            path = uploadPath.getPath() + "/" + path.substring(path.lastIndexOf("download/") + 9);
            Path filePath = Paths.get(path);
            File toFile = filePath.toFile();
            boolean exists = toFile.exists();
            if (exists) {
                Files.delete(filePath);
            }
        } catch (IOException e) {
            log.error(loggerName, "delete file error!", e);
            return Message.error(1, "删除失败");
        }
        return Message.success("删除成功");
    }

    //删除文件加数据库
    @ApiOperation(value = "删除文件加公告数据库", notes = "删除文件加公告数据库。")
    @ResponseBody
    @RequestMapping(value = {"/deleteFileDb"}, method = RequestMethod.GET)
    @Transactional(rollbackFor = Exception.class)
    public Message deleteFileDb(
            @ApiParam(value = "文件路径名称。", required = true) @RequestParam("path") String path,
            @RequestParam(value = "fileId", required = false) String fileId, HttpServletRequest request) {
        try {
            //先删数据库
            if (StringUtils.isNotBlank(fileId)) {
                int i = tbEnterpriseAnnouncementFileService.removeByfileId(fileId);
                if (i == 0) {
                    return Message.error(1, "删除失败");
                }
            }
            path = uploadPath.getPath() + "/" + path.substring(path.lastIndexOf("download/") + 9);
            Path filePath = Paths.get(path);
            Files.delete(filePath);

        } catch (IOException e) {
            log.error(loggerName, "delete file error!", e);
            return Message.error(1, "删除失败");
        }
        return Message.success("删除成功");
    }

    @ApiOperation(value = "删除合同文件信息", notes = "删除合同文件信息。")
    @ResponseBody
    @RequestMapping(value = {"/deleteContractFile"}, method = RequestMethod.GET)
    @Transactional(rollbackFor = Exception.class)
    public Message deleteContractFile(
            @ApiParam(value = "文件路径名称。", required = true) @RequestParam("path") String path,
            @RequestParam(value = "fileId", required = false) String fileId, HttpServletRequest request) {
        try {
            if (StringUtils.isNotBlank(fileId)) {
                if (tbContractFileMapper.deleteById(fileId) != 1) {
                    return Message.error(1, "删除数据库文件信息失败");
                }
            }
            path = uploadPath.getPath() + "/" + path.substring(path.lastIndexOf("download/") + 9);
            Path filePath = Paths.get(path);
            Files.delete(filePath);
        } catch (IOException e) {
            log.error(loggerName, "delete file error!", e);
            return Message.error(1, "删除失败");
        }
        return Message.success("删除成功");
    }

       @ApiOperation(value = "删除文件信息", notes = "删除文件信息。")
    @ResponseBody
    @RequestMapping(value = {"/deletePatentFile"}, method = RequestMethod.GET)
    @Transactional(rollbackFor = Exception.class)
    public Message deletePatentFile(
            @ApiParam(value = "文件路径名称。", required = true) @RequestParam("path") String path,
            @RequestParam(value = "patentFileId", required = false) String patentFileId,
            @RequestParam(value = "uploadType", required = false) Integer uploadType,HttpServletRequest request) throws Exception {
        try {

            if (!StringUtils.isBlank(patentFileId) && !"null".equals(patentFileId)) {
                if("2".equals(String.valueOf(uploadType))) {
                    tbPamPatentOverseasFileMapper.delById(new Long(patentFileId));
                } else if(patentFileMapper.deleteById(patentFileId) != 1) {
                    throw new Exception("删除数据库文件信息");
                }

            }
            path = uploadPath.getPath() + "/" + path.substring(path.lastIndexOf("download/") + 9);
            Path filePath = Paths.get(path);
            Files.delete(filePath);
        } catch (IOException e) {
            log.error(loggerName, "delete file error!", e);
            return Message.error("删除失败");
        }
        return Message.success("删除成功");
    }

       /**
           * @Description:  删除文件OA答复模块信息
           * @Param:
           * @return:
           * @Author: liuqinghua
           * @Date: 2021/8/3
           */
    @ApiOperation(value = "删除文件OA答复模块信息", notes = "删除文件OA答复模块信息")
    @ResponseBody
    @RequestMapping(value = {"/deleteOAPatentFile"}, method = RequestMethod.GET)
    @Transactional(rollbackFor = Exception.class)
    public Message deleteOAPatentFile(
            @ApiParam(value = "文件路径名称。", required = true) @RequestParam("path") String path,
            @RequestParam(value = "id", required = false) Long id,
            @RequestParam(value = "modelType", required = false) Integer modelType,HttpServletRequest request) throws Exception {
        try {

            if (!StringUtils.isBlank(id) && !"null".equals(id)) {
                if("1".equals(String.valueOf(modelType))) {
                    tbPamPatentOaCorrectionFileMapper.delById(id);
                }
            }
            path = uploadPath.getPath() + "/" + path.substring(path.lastIndexOf("download/") + 9);
            Path filePath = Paths.get(path);
            Files.delete(filePath);
        } catch (IOException e) {
            log.error(loggerName, "delete file error!", e);
            return Message.error("删除失败");
        }
        return Message.success("删除成功");
    }


    /**
     * * 查看文件
     *
     * @return
     */
    @GetMapping("/preview")
    public ResponseEntity<byte[]> display(@RequestParam("path") String path) throws Exception {

        path = uploadPath.getPath() + "/" + path.substring(path.lastIndexOf("download/") + 9);
        Path path1 = Paths.get(path);
        File file = path1.toFile();


        String filename = file.getName();
        byte[] bytes = FileUtils.file2byte(file);
        String mediaType = this.getMediaType(filename);

        HttpHeaders headers = new HttpHeaders();
        HttpStatus statusCode = HttpStatus.OK;
        headers.add("Content-Type", mediaType);
        headers.add("Content-Disposition",
                String.format("inline; filename=\"%s\"", java.net.URLEncoder.encode(filename, "UTF-8")));

        ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(bytes, headers, statusCode);
        return entity;
    }

    protected String getMediaType(String fileName) {
        if (fileName.endsWith("swf") || fileName.endsWith("fla")) {
            return "application/x-shockwave-flash";
        } else if (fileName.endsWith("png")) {
            return "image/png";
        } else if (fileName.endsWith("jpg")) {
            return "image/jpeg";
        } else if (fileName.endsWith("mp4")) {
            return "video/mp4";
        } else if (fileName.endsWith("mp3")) {
            return "audio/mp3";
        } else if (fileName.endsWith("ogg")) {
            return "audio/ogg";
        } else if (fileName.endsWith("pdf")) {
            return "application/pdf";
        } else if (fileName.endsWith("docx")) {
            return "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
        } else if (fileName.endsWith("doc")) {
            return "application/msword";
        } else {
            return "application/octet-stream";
        }
    }

    protected boolean isAttechment(String fileName) {
        if (fileName.endsWith("swf") || fileName.endsWith("fla") || fileName.endsWith("mp4")) {
            return false;
        } else {
            return true;
        }
    }

}
